#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <linux/watchdog.h>
#include "serial.h"


int open_com(char *path)
{
    int fd;
    //block method
    int flags = O_RDWR | O_NOCTTY;
    fd = open(path,flags);
    if(fd < 0){
        perror("open serial,port\n");
        return -1;
    }    
    return fd;
}
int set_com(int fd, const com_opt_t *com_opt)
{
   	struct termios new_cfg, old_cfg;
	int speed;

	if (tcgetattr(fd, &old_cfg) != 0) {
		perror("tcgetattr");
		return -1;
	}

	new_cfg = old_cfg;
	cfmakeraw(&new_cfg);
	new_cfg.c_cflag &= ~CSIZE;
	//设置波特率
	switch (com_opt->baud_rate)
	{
	case 1200:
		speed = B1200;
		break;
	case 2400:
		speed = B2400;
		break;
	case 4800:
		speed = B4800;
		break;
	case 9600:
		speed = B9600;
		break;
	case 19200:
		speed = B19200;
		break;
	case 38400:
		speed = B38400;
		break;
	case 57600:
		speed = B57600;
		break;
	default:
	case 115200:
		speed = B115200;
		break;
	}

	cfsetispeed(&new_cfg, speed);
	cfsetospeed(&new_cfg, speed);

	//设置数据位
	switch (com_opt->data_bits)
	{
	case 7:
		new_cfg.c_cflag |= CS7;
		break;
	case 8:
		new_cfg.c_cflag |= CS8;
		break;
	}
	//设置校验位
	switch (com_opt->parity)
	{
	default:
	case 'n':
	case 'N':
	{
		new_cfg.c_cflag &= ~PARENB;
		new_cfg.c_iflag &= ~INPCK;
	}
	break;

	case 'o':
	case 'O':
	{
		new_cfg.c_cflag |= (PARODD | PARENB);
		new_cfg.c_iflag |= INPCK;
	}
	break;

	case 'e':
	case 'E':
	{
		new_cfg.c_cflag |= PARENB;
		new_cfg.c_cflag &= ~PARODD;
		new_cfg.c_iflag |= INPCK;
	}
	break;

	case 's':
	case 'S':
	{
		new_cfg.c_cflag &= ~PARENB;
		new_cfg.c_cflag &= ~CSTOPB;
	}
	break;
	}

	//设置停止位
	switch (com_opt->stop_bits)
	{
	default:
	case 1:
		new_cfg.c_cflag &= ~CSTOPB;
		break;
	case 2:
		new_cfg.c_cflag |= CSTOPB;
		break;
	}

	//设置等待时间和最小接收字符
	new_cfg.c_cc[VTIME] = 10;     //串口自带超时机制，read的时候，返回值为0超时，超时10*100ms=1s；读到数据立即返回
	new_cfg.c_cc[VMIN] = 0;

	tcflush(fd, TCIFLUSH);

	if (0 != tcsetattr(fd, TCSANOW, &new_cfg)) {
		perror("tcsetattr");
		return -1;
	}
	return 0;

}